Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

219
Vistas
"JavaScript - The Definitive Guide" - "The call() and apply() Methods"

I've tried out this code and it doesn't work:

function benchmark(n) {
  let sum = 0;
  for(let i = 1; i <= n; i++) sum += i;
  return sum;
}

function trace(o, m) {
  let original = o[m];
  o[m] = function(...args) {
    console.log(new Date(), "Entering:", m);
    let result = original.apply(this, args);
    console.log(new Date(), "Exiting:", m);
    return result;
  };
}

obj = {};
benchmark.call(obj);
trace(obj, "benchmark");
obj.benchmark(1000000);
obj["benchmark"](1000000);

The error is Uncaught TypeError: Cannot read properties of undefined (reading 'apply') at Object.o.<computed> [as benchmark]. This error happens at let result = original.apply(this, args); because it was indicated by the error line number in the Console.

This error is not resolved if I use apply() in benchmark.call(obj):

benchmark.apply(obj);

This error is only resolved if I use this:

obj.benchmark = benchmark;

I extract this from "JavaScript - The Definitive Guide":

call() and apply() allow you to indirectly invoke a function as if it were a method of some other object. The first argument to both call() and apply() is the object on which the function is to be invoked; this argument is the invocation context and becomes the value of the this keyword within the body of the function. To invoke the function f() as a method of the object o (passing no arguments), you could use either call() or apply():

f.call(o);
f.apply(o);

So, why wouldn't benchmark.call(obj); or benchmark.apply(obj); work in my code?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda